<?php

/**
 * XFramework
 *
 * @author Diogo Dias Barreiros
 */
final class Layout {

    /**
     *
     * @var LayoutManager
     */
    private static $instance = null;
    /**
     *
     * @var string
     */
    private $layout = null;
    /**
     *
     * @var array
     */
    private $vars = array();

    /**
     *
     * @return Layout
     */
    public static function getInstance() {
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function set($varName, $varValue, $htmlClass = null, $htmlTag = 'div') {
        if (!is_null($htmlClass)) {
            $varValue = '<' . $htmlTag . ' class="' . $htmlClass . '">' . $varValue . '</' . $htmlTag . '>';
        }
        $this->vars[$varName] = &$varValue;
    }

    public function setView($areaName, $viewPath, $viewName) {
        $this->views[$areaName] = array($viewPath, $viewName);
    }

    public function setLayout($layoutName) {
        $this->layout = $layoutName;
    }

    public function renderLayout() {
        if (is_null($this->layout)) {
            $layout = Config::get('Layout.default', true);
            if (is_null($layout)) {
                $layout = 'default';
            }
            $this->layout = $layout;
        }
        self::parseView('layouts' . DIRECTORY_SEPARATOR . $this->layout . '.phtml');
    }

    private function parseView($viewPath) {
        $__viewPath = VIEW_PATH . $viewPath;
        foreach ($this->vars as $key => $value) {
            $$key = $value;
        }
        $Html = Html::getInstance();
        $Layout = $this;
        include $__viewPath;
    }

    public function area($name) {
        if (isset($this->views[$name])) {
            $this->parseView(implode('/', $this->views[$name]).'.phtml');
        }
    }
    
    public function element($name) {
        $this->parseView('elements/'.$name.'.phtml');
    }

}

?>
